#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Download script for TVBox files
Downloads specified files from ctv.mangzhexuexi.com
"""

import os
import sys
import urllib.request
import urllib.error
from pathlib import Path

# Fix Windows console encoding
if sys.platform == 'win32':
    try:
        sys.stdout.reconfigure(encoding='utf-8')
    except:
        pass

# Base URLs
BASE_URL_TVBOX = "https://15414.kstore.space/TVBox/"
BASE_URL_ROOT = "https://15414.kstore.space/"

# File configurations: (URL, destination_path)
DOWNLOADS = [
    # Files to download to ./TVBox/
    (BASE_URL_TVBOX + "emby.json", "./TVBox/emby.json"),
    (BASE_URL_TVBOX + "custom_spider_modified.jar", "./TVBox/custom_spider_modified.jar"),

    # Files to download to ./
    (BASE_URL_ROOT + "%E5%8D%95%E7%BA%BF%E8%B7%AF.zip", "./单线路.zip"),
    (BASE_URL_ROOT + "TVBox.zip", "./TVBox.zip"),
]


def download_file(url, destination):
    """
    Download a file from URL to destination path.

    Args:
        url: Source URL
        destination: Destination file path

    Returns:
        True if successful, False otherwise
    """
    try:
        # Create directory if it doesn't exist
        dest_path = Path(destination)
        dest_path.parent.mkdir(parents=True, exist_ok=True)

        print(f"Downloading: {url}")
        print(f"  -> {destination}")

        # Download the file
        urllib.request.urlretrieve(url, destination)

        # Get file size
        file_size = os.path.getsize(destination)
        print(f"  ✓ Downloaded successfully ({file_size:,} bytes)\n")
        return True

    except urllib.error.URLError as e:
        print(f"  ✗ URL Error: {e.reason}\n")
        return False
    except urllib.error.HTTPError as e:
        print(f"  ✗ HTTP Error {e.code}: {e.reason}\n")
        return False
    except Exception as e:
        print(f"  ✗ Error: {str(e)}\n")
        return False


def main():
    """Main function to download all configured files."""
    print("=" * 60)
    print("TVBox File Download Script")
    print("=" * 60)
    print()

    success_count = 0
    failed_count = 0

    for url, destination in DOWNLOADS:
        if download_file(url, destination):
            success_count += 1
        else:
            failed_count += 1

    # Summary
    print("=" * 60)
    print(f"Download Summary:")
    print(f"  ✓ Successful: {success_count}")
    print(f"  ✗ Failed: {failed_count}")
    print(f"  Total: {len(DOWNLOADS)}")
    print("=" * 60)

    return 0 if failed_count == 0 else 1


if __name__ == "__main__":
    exit(main())
